import 'dart:convert';
import 'package:merchants/models/merchant.dart';

class WeChatUserInfo {
  final String openid;
  final String nickname;
  final String avatar;
  final int sex;
  final String province;
  final String city;
  final String country;
  final String unionid;
  final bool? approved;
  final bool? hasRecord;
  final String? role;
  final List<String>? scopes;
  final String? token;

  WeChatUserInfo({
    required this.openid,
    required this.avatar,
    required this.sex,
    required this.province,
    required this.city,
    required this.country,
    required this.unionid,
    required this.nickname,
    this.approved,
    this.hasRecord,
    this.role,
    this.scopes,
    this.token,
  });

  factory WeChatUserInfo.fromJson(Map<String, dynamic> json) {
    return WeChatUserInfo(
      openid: json['openid'] as String,
      nickname: json['nickname'] as String,
      avatar: json['avatar'] as String,
      sex: json['sex'] as int,
      province: json['province'] as String,
      city: json['city'] as String,
      country: json['country'] as String,
      unionid: json['unionid'] as String,
      approved: json['approved'] as bool?,
      hasRecord: json['hasRecord'] as bool?,
      role: json['role'] as String?,
      scopes: (json['scopes'] as List?)?.cast<String>(),
      token: json['token'] as String?,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'openid': openid,
      'nickname': nickname,
      'avatar': avatar,
      'sex': sex,
      'province': province,
      'city': city,
      'country': country,
      'unionid': unionid,
      'approved': approved,
      'hasRecord': hasRecord,
      'role': role,
      'scopes': scopes,
      'token': token,
    };
  }

  static WeChatUserInfo? fromSharedPreferences(String? jsonString) {
    if (jsonString == null) return null;
    try {
      final json = jsonDecode(jsonString);
      return WeChatUserInfo.fromJson(json);
    } catch (e) {
      return null;
    }
  }

  String toSharedPreferences() {
    return jsonEncode(toJson());
  }
}
